package com.lej.qrcode

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Vibrator
import android.util.Log
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cn.bingoogolapple.qrcode.core.QRCodeView
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder
import cn.bingoogolapple.qrcode.zxing.ZXingView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.atomic.AtomicBoolean

/**扫描二维码*/
class QRCodeActivity : AppCompatActivity() {
    var mQRCodeView: ZXingView? = null
    var ivQrcodeShow: ImageView? = null

    companion object {
        fun start(ctx: Activity) {
            val intent = Intent(ctx, QRCodeActivity::class.java)
            ctx.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_qrcode)
        //Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
        mQRCodeView = findViewById(R.id.qrcode_view)
        ivQrcodeShow = findViewById(R.id.iv_qrcode_view)
        mQRCodeView?.setDelegate(object : QRCodeView.Delegate {
            override fun onScanQRCodeSuccess(result: String?) {
                Log.e("sss", "qrcode data result:$result")
                GlobalScope.launch { result?.createBitMap() }
                vibrate()
                mQRCodeView?.startSpot() // 开始识别
            }

            override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {
                // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
                // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
                var tipText = mQRCodeView!!.scanBoxView.tipText
                val ambientBrightnessTip = "\n环境过暗，请打开闪光灯"
                if (isDark) {
                    if (!tipText.contains(ambientBrightnessTip)) {
                        mQRCodeView!!.scanBoxView.tipText = tipText + ambientBrightnessTip
                    }
                } else {
                    if (tipText.contains(ambientBrightnessTip)) {
                        tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip))
                        mQRCodeView!!.scanBoxView.tipText = tipText
                    }
                }
            }

            override fun onScanQRCodeOpenCameraError() {
                Toast.makeText(this@QRCodeActivity, "打开相机失败", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun vibrate() {
        val vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(200)
    }

    override fun onStart() {
        super.onStart()
        mQRCodeView?.startCamera() // 打开后置摄像头开始预览，但是并未开始识别
//        mZBarView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别

        mQRCodeView?.startSpotAndShowRect() // 显示扫描框，并开始识别
    }

    override fun onDestroy() {
        super.onDestroy()
        mQRCodeView?.onDestroy() // 销毁二维码扫描控件
    }

    override fun onStop() {
        super.onStop()
        mQRCodeView?.stopCamera() // 销毁二维码扫描控件
    }

    private val isCreate = AtomicBoolean(false)

    private suspend fun String.createBitMap() {
        if (isCreate.compareAndSet(false, true)) {
            val bitmap = withContext(Dispatchers.IO) {
                QRCodeEncoder.syncEncodeQRCode(this@createBitMap, 500, 500)
            }
            withContext(Dispatchers.Main) {
                ivQrcodeShow?.setImageBitmap(bitmap)
                isCreate.set(false)
            }
        }
    }
}